package com.hmall.cart.listener;

import com.hmall.cart.service.ICartService;
import com.hmall.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author LiYang
 * @desc 订单创建删除购物车选购的商品
 * @date 2024/10/6 19:13
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class OrderCreateListener {

    private final RabbitTemplate rabbitTemplate;

    private final ICartService cartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "cart.clear.queue", durable = "true"),
            exchange = @Exchange(name = "trade.topic",type = ExchangeTypes.DIRECT),
            key = "order.create"
    ))
    public void listenOrderCreate(List<Long> ItemIds, Message message) {
        Long userId = message.getMessageProperties().getHeader("userId");
        log.info("监听到订单创建，正在清理userId为{}的购物车 ", userId);
        UserContext.setUser(userId);
        cartService.removeByItemIds(ItemIds);
    }
}
